#!/bin/bash

# 会议视频文字自动记录系统安装脚本

set -e

echo "=== 会议视频文字自动记录系统安装脚本 ==="

# 检查Python版本
python_version=$(python3 --version 2>&1 | awk '{print $2}' | cut -d. -f1,2)
required_version="3.9"

if [ "$(printf '%s\n' "$required_version" "$python_version" | sort -V | head -n1)" != "$required_version" ]; then
    echo "错误: 需要Python 3.9或更高版本，当前版本: $python_version"
    exit 1
fi

echo "✓ Python版本检查通过: $python_version"

# 创建虚拟环境
if [ ! -d "venv" ]; then
    echo "创建Python虚拟环境..."
    python3 -m venv venv
fi

# 激活虚拟环境
source venv/bin/activate
echo "✓ 虚拟环境已激活"

# 升级pip
pip install --upgrade pip

# 安装依赖
echo "安装Python依赖包..."
pip install -r requirements.txt
echo "✓ Python依赖安装完成"

# 创建必要的目录
echo "创建项目目录..."
mkdir -p data logs models temp exports uploads
echo "✓ 目录创建完成"

# 检查配置文件
if [ ! -f "config/config.yaml" ]; then
    echo "创建默认配置文件..."
    cp config/config.yaml config/config.yaml.backup 2>/dev/null || true
fi

# 下载模型文件（可选）
echo "检查模型文件..."
if [ ! -f "models/yolov8s.onnx" ]; then
    echo "警告: YOLOv8模型文件不存在"
    echo "请手动下载模型文件到 models/ 目录"
    echo "YOLOv8: https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s.onnx"
fi

# 检查Redis
echo "检查Redis服务..."
if command -v redis-server &> /dev/null; then
    echo "✓ Redis已安装"
    if ! pgrep -x "redis-server" > /dev/null; then
        echo "启动Redis服务..."
        redis-server --daemonize yes
    fi
else
    echo "警告: Redis未安装，请安装Redis服务"
    echo "Ubuntu/Debian: sudo apt-get install redis-server"
    echo "CentOS/RHEL: sudo yum install redis"
    echo "macOS: brew install redis"
fi

# 初始化数据库
echo "初始化数据库..."
python -c "
from src.storage.database import DatabaseManager
try:
    db = DatabaseManager()
    print('✓ 数据库初始化成功')
except Exception as e:
    print(f'✗ 数据库初始化失败: {e}')
"

# 运行测试
echo "运行基础测试..."
python -c "
import sys
sys.path.append('.')
try:
    from src.core import config
    print('✓ 配置模块加载成功')
    from src.detection import YOLODetector
    print('✓ 检测模块加载成功')
    from src.storage import DatabaseManager
    print('✓ 存储模块加载成功')
    print('✓ 所有核心模块加载成功')
except Exception as e:
    print(f'✗ 模块加载失败: {e}')
    sys.exit(1)
"

echo ""
echo "=== 安装完成 ==="
echo ""
echo "下一步操作:"
echo "1. 下载模型文件到 models/ 目录"
echo "2. 修改 config/config.yaml 配置文件"
echo "3. 启动服务: python -m src.main"
echo "4. 访问 http://localhost:8000 查看API文档"
echo ""
echo "Docker部署:"
echo "docker-compose up -d"
echo ""
echo "运行测试:"
echo "pytest tests/ -v"
echo ""
